<template>
    <van-nav-bar title="商品详情" left-arrow @click-left="onClickLeft" :fixed="true" />
    <div class="vannavbar"></div>
    <div class="ProductDetails">
        <div class="ProductDetails_img"> <img :src="ProductModel.Picture" alt=""> </div>
        <div class="ProductDetails_form">
            <div class="nav_week">
                <div class="week_a">
                    <div class="name"> {{ProductModel.Name}} </div>
                    <div class="chou"> 已购买 <span>{{ProductModel.Raise}}</span> 元 </div>
                </div>
                <div class="week_b">
                    <div class="huibao"> 回报比例2%-5% </div>
                    <div class="moert"> ¥ <span> {{ProductModel.Price}}</span> </div>
                </div>
            </div>
            <div class="nav_more">
                <div class="int">
                    <div class="lf">
                        <p> 余额 </p>
                        <h5 style="color:#333333"> {{token.Wallet3}} </h5>
                    </div>
                </div>
                <div class="int">
                    <div class="lf">
                        <p> 购买金额 </p>
                        <div class="ProductDetails_stepper">
                            <van-stepper v-model="PayMoney" input-width="160px" button-size="45px" :decimal-length="2"
                                :min="ProductModel.Price||0" step="100" />
                        </div>
                    </div>
                </div>
                <div class="int">
                    <div class="lf">
                        <p> 支付金额 </p>
                        <h5 v-if="IsBalacneMoeny"> {{ PayMoneyValue}} </h5>
                        <h5 v-else> {{PayMoney}} </h5>
                    </div>
                    <!-- <div :class="[IsBalacneMoeny==true?'dk':'nk','rt']" @click="Deductionbalance()">
                        <van-icon name="checked" /> 抵扣余额
                    </div> -->
                </div>
                <div class="int">
                    <div class="lf">
                        <p> 项目详情 </p>
                        <div class="ShipToAddress">
                            {{ProductModel.Contents}}
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="ProductDetails_submit">
            <div class="cancel" @click="goCancel()"> 取消 </div>
            <div class="Alipay" @click="subumitCreate()"> 线下支付 </div>
        </div>
        <div class="form" v-html="content"></div>
    </div>
</template>

<script>
    import { defineComponent, reactive, onMounted, onBeforeMount, onBeforeUnmount, ref, toRefs, watchEffect, watch } from "vue";
    import { Toast, Notify } from 'vant';
    import { Dialog } from 'vant';
    import { useStore } from "vuex"; // ⚪️ 引入状态管理
    import { useRoute, useRouter } from "vue-router";
    import router from "@/router";
    import { GetMemberExt } from "@/network/user";
    import CryptoJS from 'crypto-js'
    import { GetProductModel, GetOrderDetail, Create, paytoken } from "@/network/order";
    export default {
        setup() {
            const store = useStore(); // 获取对象
            const route = useRoute();
            const { id } = route.query;
            const state = reactive({
                token: store.state.user.token,
                id: id,
                ProductModel: '',
                PayMoney: 0,
                PayMoneyValue: 0,
                IsBalacneMoeny: false,
                content: '',
                timer: '',
            })
            onMounted(() => {
                init();
            });
            onBeforeUnmount(() => {
                clearInterval(state.timer);
                console.log("即将销毁");
            });
            onBeforeMount(() => {

                console.log("DOM即将挂载");
            })
            // 初始化信息
            const init = () => {
                getUser();
                // 获取商品详情
                GetProductModel({
                    ProductId: state.id
                }).then((res) => {
                    var data = res.Data;
                    state.ProductModel = data
                });
            };
            // 1.2、普通监听
            watch(() => state.PayMoney, (value) => {
                if (state.PayMoney > state.token.Wallet3) {
                    state.PayMoneyValue = (state.PayMoney - state.token.Wallet3).toFixed(2)
                } else {
                    state.PayMoneyValue = 0
                }
            });
            //是否抵扣余额
            const Deductionbalance = () => {
                state.IsBalacneMoeny = !state.IsBalacneMoeny
            };
            // 创建订单
            const subumitCreate = () => {
                Dialog.confirm({
                    title: '提示',
                    message: '确定购买该产品吗？',
                }).then(() => {
                    subumitCreateConfim();
                }).catch(() => { });

            };
            // 提交订单
            const subumitCreateConfim = () => {
                clearInterval(state.timer);
                var PayMoney = state.IsBalacneMoeny ? state.PayMoney : state.PayMoneyValue;
                const toast = Toast.loading({
                    duration: 0,
                    forbidClick: true,
                    message: '订单提交中...',
                });
                var params = {
                    MemberId: state.token.ID,
                    ProductId: state.id,
                    PayMoney: state.PayMoney,
                    IsBalacneMoeny: state.IsBalacneMoeny
                }
                Create(params).then((res) => {
                    var data = res.Data;
                    if (res.Code == 0) {
                        state.content = '';
                        toast.clear()
                        //0 余额 1 支付宝 ，2组合  (1 和2  需要调起支付 )
                        if (data.RealPay == 0) {
                            Toast.success('捐助成功');
                            router.push({ path: "/myinvestment" });
                        } else {
                            console.log(data);
                            paytokenZfb(data.ID);
                            // state.timer = setInterval(function () {
                            //     GetOrderDetailfun(data.ID);
                            // }, 1000)
                        }
                    } else {
                        toast.clear()
                    }
                    getUser();
                });
            };
            //调起线下支付
            const paytokenZfb = (orderCode) => {
                const toast = Toast.loading({
                    duration: 0,
                    forbidClick: true,
                    message: '支付宝启动中...',
                });
                var params = {
                    MemberId: state.token.ID,
                    orderCode: orderCode,
                    payWay: 1,
                    tradeType: 1
                }
                paytoken(params).then((res) => {
                    if (res.Code == 0) {
                        // var Token = decryption(res.Data.Token);
                        var OrderCode = res.Data.OrderCode;
                        var Token = res.Data.Token;
                        toast.clear()
                        console.log(Token)
                        window.requesTag.paytokenZfb(Token)
                        // state.content = Token;
                        // setTimeout(() => {
                        //     document.forms[0].submit()//通过submit()传递给服务器，进行响应
                        // }, 100)
                        // const div = document.createElement("div");
                        // div.innerHTML = Token; //此处form就是后台返回接收到的数据
                        // document.body.appendChild(div);
                        // document.forms[0].submit();
                    } else {
                        toast.clear()
                    }
                });
            }
            const GetOrderDetailfun = (orderCode) => {
                var params = {
                    orderId: orderCode
                }
                GetOrderDetail(params).then((res) => {
                    if (res.Code == 0) {
                        if (res.Data.Status > 0) {
                            clearInterval(state.timer);
                            router.push({ path: "/myinvestment" });
                        }
                    } else {

                    }
                });
            }
            const decryption = (str) => {
                return CryptoJS.enc.Base64.parse(str).toString(CryptoJS.enc.Utf8);
            }
            //获取用户信息 更新余额
            const getUser = () => {
                store.dispatch("GetMemberInfo", { Id: store.state.user.token.ID }).then((res) => {
                    state.token = res.Data
                }).catch(() => { });
            }
            const goCancel = () => {
                router.push({ path: "/Commodity" });
            };
            const onClickLeft = () => {
                router.push({ path: "/Commodity" });
            };

            return {
                ...toRefs(state),
                onClickLeft,
                goCancel,
                Deductionbalance,
                subumitCreate,
                subumitCreateConfim,
                getUser,
                paytokenZfb,
                decryption
            };
        },
    };
</script>

<style scoped>

</style>